package com.cy.pj.module.controller;

import com.cy.pj.module.pojo.ResponseResult;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class JsonController {


    @RequestMapping("/doPrintResponseString")
    @ResponseBody
    public void doPrintResponseString(HttpServletResponse response) throws IOException {
        ResponseResult result=new ResponseResult();
        result.setCode(300);
        result.setMessage("服务端处理成功了");

        //构建jacson中的ObjectMapper对象，基于此对象将pojo对象转换为JSON字符串
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonStr=objectMapper.writeValueAsString(result);

        //设置响应数据的编码
        response.setCharacterEncoding("utf-8");
        //告诉客户端，要向它响应的数据类型为text/html,编码为utf-8,请以这种编码进行数据呈现
        response.setContentType("text/html:charset=utf-8");

        //获取输出流对象
        PrintWriter out=response.getWriter();

        //基于流对象将json串写到客户端
        out.println(jsonStr);
    }

    @RequestMapping("/doPrintJsonString")
    @ResponseBody
    public String doPrintJsonString(){
        String jsonStr="{code:200,message:\"ok\"}";
        return jsonStr;
    }



    @RequestMapping("/doConverResponseToJson")
    @ResponseBody//表示不再将响应结果理解为view,并将响应结果转换为JSON格式（前提是必须满足转换为JSON格式数据的条件），写到响应体，响应到客户端
    public ResponseResult doConverResponseToJson(){
        ResponseResult result=new ResponseResult();
        result.setCode(200);
        result.setMessage("ok");
        return result;/*此对象在返回时，spring web模块会调用Jackson API，将返回值转换为JSON格式字符串*/
    }

    @RequestMapping("/doConverListToJson")
    @ResponseBody
    public List<Map<String,Object>> doConverListToJson(){
        List<Map<String,Object>>list=new ArrayList<>();
        Map<String,Object> map=new HashMap<>();
        map.put("name", "tony");
        map.put("state",true );
        list.add(map);
        map=new HashMap<>();
        map.put("name", "Jason");
        map.put("state", true);
        list.add(map);
        return list;
    }

}
